import request from '@/utils/request'
import axios from 'axios'

export function login(data) {
  data['grant_type'] = 'password_code'
  data['deviceId'] = '123123123'
  data['validCode'] = '12ab'
  /**
   * axios 默认是 Payload 格式数据请求，但有时候后端接收参数要求必须是 Form Data 格式的，所以我们就得进行转换。
   * Payload 和 Form Data 的主要设置是根据请求头的 Content-Type 的值来的。
   * Payload Content-Type: 'application/json; charset=utf-8'
   * Form Data Content-Type: 'application/x-www-form-urlencoded'
   * 参考链接: https://www.cnblogs.com/jeor/p/14142937.html
   */
  return request({
    // url: '/vue-element-admin/user/login',
    url: '/uaa/oauth/token',
    method: 'post',
    data,
    transformRequest: [
      (data) => {
        let ret = ''
        for (const it in data) {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
        ret = ret.substring(0, ret.lastIndexOf('&'))
        return ret
      }
    ],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}

export function getInfo() {
  return request({
    url: '/user/users/current',
    method: 'get'
  })
}

/**
 * 前端简单实现，待将来优化
 * @param token
 * @returns {AxiosPromise<any>}
 */
export function logout(token) {
  const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 5000 // request timeout
  })
  return service.request({
    url: '/uaa/oauth/check_token?token=' + token,
    method: 'post'
  })
}
